package ua.edu.nuos.jeetraining2012.automator.core.runner.feed.adapter.impl;

import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import ua.edu.nuos.jeetraining2012.automator.core.runner.feed.adapter.api.IFeedAdapter;
import ua.edu.nuos.jeetraining2012.automator.core.vo.message.Message;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * User: timur.yarosh
 * Date: 26.06.13
 * Time: 1:59
 */
public class RssFeedAdapter implements IFeedAdapter {
    private String url;
    private long polingTime;
    private SyndFeed oldFeed;
    private SyndFeed newFeed;

    public RssFeedAdapter(String url, long polingTime) {
        this.url = url;
        this.polingTime = polingTime;
    }

    @Override
    public List<Message> messages() {
        List<Message> messages = null;
        messages = makeMessagesList(newFeed);
        return messages;
    }

    private List<Message> makeMessagesList(SyndFeed feed) {
        List<Message> messages = new ArrayList<Message>();
        List entries = feed.getEntries();
        for (Object entry : entries) {
            SyndEntry syndEntry = (SyndEntry) entry;
            Message message = buildMessage(syndEntry);
            messages.add(message);
        }
        return messages;
    }

    private Message buildMessage(SyndEntry syndEntry) {
        Message message = new Message();
        message.setText(syndEntry.getTitle() + "\n"
                + syndEntry.getDescription() + "\n"
                + syndEntry.getAuthor());
        return message;
    }

    @Override
    public void waitMessage() {
        while (this.oldFeed.equals(newFeed)) {
            try {
                newFeed = parseFeed(url);
                Thread.sleep(polingTime);
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            } catch (FeedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
        oldFeed = newFeed;
    }

    private SyndFeed parseFeed(String url) throws IOException, FeedException {
        return new SyndFeedInput().build(new XmlReader(new URL(url)));
    }
}
